package com.xiashitech.agent.rule.usermatch.inst;

import com.google.auto.service.AutoService;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.rule.usermatch.base.UserInfoMatchRule;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import ognl.Ognl;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

//@AutoService(UserInfoMatchRule.class)
public class XSOAuth2AccessTokenUserMatch<REQUEST> implements UserInfoMatchRule<REQUEST> {
    @Override
    public UserRequest extractUserInfo(REQUEST request) {
        if (request == null || !(request.getClass().getInterfaces().length > 0 && Arrays.stream(request.getClass().getInterfaces()).anyMatch(interfaceName -> "org.springframework.security.oauth2.common.OAuth2AccessToken".equals(interfaceName.getName())))) {
            return UserRequest.builder().build();
        }
        UserRequest userRequest = UserRequest.builder().requestDate(String.valueOf(new Date().getTime())).build();
        Object oAuth2AccessToken = request;
        try {
            Map<String, Object> additionalInformationMap = (Map)oAuth2AccessToken.getClass().getMethod("getAdditionalInformation").invoke(oAuth2AccessToken);
            if(!additionalInformationMap.isEmpty()) {
                String userIdPath = AgentConfigDTO.getConfig().getUseridpath().get(StartConfig.getParamValueFromKey(StartConfig.systemId));
                Object value = Ognl.getValue(userIdPath, additionalInformationMap);
                if(value != null) {
                    userRequest.setUserid(value.toString());
                }
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return userRequest;
    }

    @Override
    public Integer getOrder() {
        return 7;
    }
}
